<template>
  <view class="wh_750 flex flex-column align-center bg_FFFFFF pageHeight">
    <s-header-title is-display-back title="手机号登录"></s-header-title>
    <view class="hW_160"></view>
    <view class="page-msg wh_606">
      <view class="title">
        {{ '手机号登录' }}
      </view>
      <view class="tip">
        {{ '首次登录会自动注册' }}
      </view>
    </view>
    <view class="page-form">
      <view class="item">
        <input type='number' placeholder='填写手机号码' placeholder-class='placeholder' v-model="page.phone"
               :maxlength="11"></input>
      </view>
      <view class="item flex align-center justify-between">
        <input type='number' placeholder='填写验证码' placeholder-class='placeholder' :maxlength="4"
               class="codeIput" v-model="page.captcha"></input>
        <view class="line">
        </view>
        <view class="flex-sub flex align-center justify-center">
          <button
            class="ss-reset-button code-btn code-btn-start mr_30 color_FF4206 fs_32"
            :disabled="state.isMobileEnd"
            :class="{ 'code-btn-end': state.isMobileEnd }"
            @tap="getSmsCode('smsLogin', page.phone)"
          >
            {{ getSmsTimer('smsLogin') }}
          </button>
        </view>
      </view>
      <view class="btn" @click="submitData" v-if="page.protocol">
        {{ '立即登录' }}
      </view>
      <view class="btn" @click="openLoginPopup" v-else>
        {{ '立即登录' }}
      </view>
    </view>
    <view class="protocol flex align-center justify-center  z-1">
      <checkbox-group @change="changeCheck">
        <checkbox style="border-radius: 50%;transform:scale(0.7)"
                  :checked="page.protocol ? true : false"
                  color="#ff4206"
        />
      </checkbox-group>
      我已阅读并遵守
      <text class="font-num"
            @tap.stop="onProtocol(appInfo.user_protocol.id, appInfo.user_protocol.title)"
      >
        《{{ appInfo.user_protocol.title }}》
      </text>
      与
      <text class="font-num" @tap.stop="onProtocol(appInfo.privacy_protocol.id, appInfo.privacy_protocol.title)">
        《{{ appInfo.privacy_protocol.title }}》
      </text>
    </view>

    <first_popup ref="loginFirstPopup">
      <view class="loginFirstPopup">
        <view class="loginFirstPopup_header">
          <view class="loginFirstPopup_header_tips" style="padding: 0 24rpx">
            <text class="loginFirstPopup_header_tips_standard">为了让您更好的使用拾亲，请充分阅读并同意
            </text>
            <text class="loginFirstPopup_header_tips_click font-num"
                  @tap.stop="onProtocol(appInfo.user_protocol.id, appInfo.user_protocol.title)">
              《{{ appInfo.user_protocol.title }}》
            </text>
            <text class="loginFirstPopup_header_tips_standard">和</text>
            <text class="loginFirstPopup_header_tips_click font-num"
                  @tap.stop="onProtocol(appInfo.privacy_protocol.id, appInfo.privacy_protocol.title)">
              《{{ appInfo.privacy_protocol.title }}》
            </text>
          </view>
        </view>
        <view class="loginFirstPopup_bottom flex justify-around">
          <button class="loginFirstPopup_bottom_closeButton flex align-center justify-center" hover-class="none"
                  @tap="closeLoginFirstPopup">
            <text class="loginFirstPopup_bottom_closeButton_text">取消</text>
          </button>
          <button hover-class="none"
                  @tap="login"
                  class="loginFirstPopup_bottom_confirmButton bg-color flex align-center justify-center">
            <text class="loginFirstPopup_bottom_confirmButton_text">同意</text>
          </button>
        </view>
      </view>
    </first_popup>
  </view>
</template>

<script setup>
  import { computed, reactive, ref } from 'vue';
  import sheep from '@/sheep';
  import { getSmsCode, getSmsTimer } from '@/sheep/hooks/useModal';
  import First_popup from '@/pages/login/components/first_popup.vue';
  import { onReady, onLoad } from '@dcloudio/uni-app';

  const page = reactive({
    phone: '',
    captcha: '',
    disabled: false,
    protocol: false,
  });

  const state = reactive({
    isMobileEnd: false,
    options: {},
  });
  const appInfo = computed(() => sheep.$store('app').info);
  const loginFirstPopup = ref();
  const isLogin = computed(() => sheep.$store('user').isLogin);

  onLoad((options) => {
    page.options = options;
    if(!isLogin.value){
      let accountList = JSON.parse(uni.getStorageSync('account-list') || '[]');
      if (accountList.length > 0) {
        uni.removeStorageSync('account-list')
      }
    }
  });

  onReady(() => {
    if (!!isLogin.value && (page.options.is_toggle != 1 && page.options.is_toggle != 3)) {
      uni.switchTab({
        url: '/pages/message/genealogy',
      });
    }
  });

  // 查看协议
  function onProtocol(id, title) {
    sheep.$router.go('/pages/public/richtext', {
      id,
      title,
    });
  }

  function changeCheck(e) {
    page.protocol = !!e.detail.value;
  }

  async function submitData() {
    if (!page.protocol) {
      loginFirstPopup._value.openPopup({
        title: '请先阅读并同意协议',
        isShowConfirm: false,
        showColseButton: false,
      });
      return;
    }
    if (!page.phone) {
      sheep.$helper.toast('请输入手机号');
      return;
    }
    if (!page.captcha) {
      sheep.$helper.toast('请输入验证码');
      return;
    }
    let accountList = JSON.parse(uni.getStorageSync('account-list') || '[]');
    let arr = accountList.filter((item) => item.account == page.phone);
    if (arr.length > 0) {
      sheep.$helper.toast('该账号已存在');
      closeLoginFirstPopup();
      return;
    }
    const { code, msg } = await sheep.$api.user.smsLogin({
      mobile: page.phone,
      code: page.captcha,
      is_toggle: page.options.is_toggle == 1 || page.options.is_toggle == 3 ? 1 : 0,
    });
    if (code == 1) {
      const userInfo = await sheep.$store('user').getInfo();
      await addAccount();

      if (!userInfo.surname || !userInfo.daimyo) {
        // #ifdef H5
        uni.redirectTo({
          url: '/pages/userData/sex',
        });
        // #endif
        // #ifndef H5
        uni.reLaunch({
          url: '/pages/userData/sex',
        });
        // #endif
      } else {
        if (page.options.is_toggle == 1) {
          uni.navigateBack();
        } else if (page.options.is_toggle == 3) {
          uni.navigateBack({
            delta: 2,
          });
        } else {
          uni.switchTab({
            url: '/pages/message/genealogy',
          });
        }
      }

      await sheep.$store('AI').setAllSessionList();
      await sheep.$store('AI').setAllFollowList();
      await sheep.$store('family').getList();
      await sheep.$store('family').getFamilyTree();
      const bind_id = computed(() => sheep.$store('AI').bind_id);
      const bind_family_id = computed(() => sheep.$store('AI').bind_family_id);
      if (!!bind_id.value) {
        await sheep.$api.user.bindParent({ parent_id: bind_id.value });
      }
      if (!!bind_family_id.value && !!isLogin.value) {
        const { code } = await sheep.$api.family.applyFamily({ family_id: bind_family_id.value });
        if (code == 1) {
          sheep.$store('AI').setBindFamilyId('');
        }
      }
    }
  }

  function openLoginPopup() {
    if (!page.phone) {
      sheep.$helper.toast('请输入手机号');
      return;
    }
    if (!page.captcha) {
      sheep.$helper.toast('请输入验证码');
      return;
    }
    loginFirstPopup._value.openPopup({
      title: '欢迎使用拾亲',
      isShowConfirm: false,
      showColseButton: false,
    });
  }

  function closeLoginFirstPopup() {
    loginFirstPopup._value.closePopup();
  }

  async function login() {
    let accountList = JSON.parse(uni.getStorageSync('account-list') || '[]');
    let arr = accountList.filter((item) => item.account == page.phone);
    if (arr.length > 0) {
      sheep.$helper.toast('该账号已存在');
      closeLoginFirstPopup();
      return;
    }
    const { code, msg } = await sheep.$api.user.smsLogin({
      mobile: page.phone,
      code: page.captcha,
      is_toggle: page.options.is_toggle == 1 || page.options.is_toggle == 3 ? 1 : 0,
    });
    if (code == 1) {
      const userInfo = await sheep.$store('user').getInfo();
      await addAccount();

      if (!userInfo.surname || !userInfo.daimyo) {
        uni.reLaunch({
          url: '/pages/userData/sex',
        });
      } else {
        if (page.options.is_toggle == 1) {
          uni.navigateBack();
        } else if (page.options.is_toggle == 3) {
          uni.navigateBack({
            delta: 2,
          });
        } else {
          uni.switchTab({
            url: '/pages/message/genealogy',
          });
        }
      }

      await sheep.$store('AI').setAllSessionList();
      await sheep.$store('AI').setAllFollowList();
      await sheep.$store('family').getList();
      await sheep.$store('family').getFamilyTree();
      const bind_id = computed(() => sheep.$store('AI').bind_id);
      const bind_family_id = computed(() => sheep.$store('AI').bind_family_id);
      if (!!bind_id.value) {
        await sheep.$api.user.bindParent({ parent_id: bind_id.value });
      }
      if (!!bind_family_id.value && !!isLogin.value) {
        const { code } = await sheep.$api.family.applyFamily({ family_id: bind_family_id.value });
        if (code == 1) {
          sheep.$store('AI').setBindFamilyId('');
        }
      }
    } else {
      closeLoginFirstPopup();
    }
  }

  async function addAccount() {
    const userInfo = await sheep.$store('user').getInfo();
    let accountList = JSON.parse(uni.getStorageSync('account-list') || '[]');
    let arr = [];
    accountList.forEach((item) => {
      arr.push(item);
    });
    arr.push({
      account: userInfo.mobile,
      avatar: userInfo.avatar,
    });
    uni.setStorageSync('account-list', JSON.stringify(arr));
  }
</script>


<style scoped lang="scss">
  .page-msg {
    z-index: 2;
    position: relative;

    .title {
      font-size: 48rpx;
      font-weight: 500;
      color: #333333;
      line-height: 68rpx;
    }

    .tip {
      font-size: 28rpx;
      font-weight: 400;
      color: #333333;
      line-height: 40rpx;
    }
  }

  .page-form {
    width: 606rpx;
    margin: 100rpx auto 0 auto;
    z-index: 2;
    position: relative;

    .item {
      height: 88rpx;
      background: #F5F5F5;
      border-radius: 45rpx;
      margin-bottom: 32rpx;

      input {
        margin: 24rpx 48rpx;
        width: 100%;
        height: 100%;
        font-size: 32rpx;
      }

      .placeholder {
        color: #BBBBBB;
        font-size: 28rpx;
      }

      input.codeIput {
        width: 300rpx;
      }

      .line {
        width: 2rpx;
        height: 28rpx;
        background: #CCCCCC;
      }

      .code {
        font-size: 28rpx;
        color: var(--view-theme);
        background-color: rgba(255, 255, 255, 0);
      }

      .code.on {
        color: #BBBBBB !important;
      }
    }

    .btn {
      width: 606rpx;
      height: 88rpx;
      background: #ff4206;
      border-radius: 200rpx 200rpx 200rpx 200rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #FFFFFF;
      line-height: 44rpx;
      margin-top: 48rpx;
      letter-spacing: 1px;
    }
  }

  .protocol {
    position: fixed;
    bottom: 52rpx;
    left: 0;
    width: 100%;
    margin: 0 auto;
    color: #999999;
    font-size: 24rpx;
    line-height: 22rpx;
    text-align: center;
    bottom: calc(52rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
    bottom: calc(52rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

    .check {
      width: 32rpx;
      height: 32rpx;
      border: 2rpx solid #D1D1D1;
      border-radius: 50%;
    }
  }

  .font-num {
    color: #ff4206;
  }

  .centralPoint {
    width: 20rpx;
    height: 20rpx;
    background: #ff4206;
    border-radius: 50%;
  }

  .loginFirstPopup {
    .loginFirstPopup_header {
      .loginFirstPopup_header_tips {
        .loginFirstPopup_header_tips_standard {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 28rpx;
          color: #000000;
        }

        .loginFirstPopup_header_tips_click {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 28rpx;
          color: #4887FF;
        }
      }
    }

    .loginFirstPopup_bottom {
      margin: 54rpx 0;

      .loginFirstPopup_bottom_closeButton {
        width: 213rpx;
        height: 80rpx;
        background: #A0A0A0;
        border-radius: 41rpx 41rpx 41rpx 41rpx;

        .loginFirstPopup_bottom_closeButton_text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 30rpx;
          color: #FFFFFF;
        }
      }

      .loginFirstPopup_bottom_confirmButton {
        width: 213rpx;
        height: 80rpx;
        background: #FF4206;
        border-radius: 41rpx 41rpx 41rpx 41rpx;

        .loginFirstPopup_bottom_confirmButton_text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 30rpx;
          color: #FFFFFF;
        }
      }
    }
  }
</style>
